﻿using BLL;
using Inspinia_MVC5.Code;
using Inspinia_MVC5.Models;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Inspinia_MVC5.Controllers
{
    [AllowCors]
    [SessionTimeOutFilter]
    public class AdjustController : AsyncController 
    {
        public JsonResult Sensor(string wellid)
        {
            R_ADJU_StructureService R_ADJU_StructureService = new R_ADJU_StructureService();
            Well2SensorService Well2SensorService = new Well2SensorService();
            R_SIGN_METER_BATT_POWService R_SIGN_METER_BATT_POWService = new R_SIGN_METER_BATT_POWService();
            List<Well2Sensor> well2sensors = new List<Well2Sensor>();
            var rasss = R_ADJU_StructureService.All().ToList();
            var rsmbps = R_SIGN_METER_BATT_POWService.FindAll(c => c.Well_ID == wellid);
            var rsmbp = rsmbps.FirstOrDefault(c => c.Time == rsmbps.Max(d => d.Time));
            well2sensors = Well2SensorService.FindAll(c => c.WELL_ID == wellid).ToList();
            List<SensorModel> sensors = new List<SensorModel>();
            foreach (var well2sensor in well2sensors)
            {
                DataTable table = new DataTable();
                using (var Db = new DBContainer())
                {
                    string sql1 = "SELECT TOP 1 * FROM R_ADJU_" + well2sensor.SENS_NAME + " WHERE Well_ID = " + wellid + " order by Time desc ";
                    table = ResultHelper.sqlQueryForDataTatable(Db.Database, sql1).Copy();
                }
                if (table.Rows.Count > 0)
                {
                    string[] chaandpow = eng2chaandpow(well2sensor.SENS_NAME.Trim(), rsmbp);
                    SensorModel sensor = new SensorModel();
                    sensor.SensorValue = new List<SensorValueModel>();
                    sensor.WellId = wellid;
                    sensor.Power = chaandpow[1].Trim();
                    sensor.SensorName = well2sensor.SENS_NAME.Trim();
                    sensor.SensorChina = chaandpow[0];
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        if (table.Columns[i].ColumnName.Contains("ID") || table.Columns[i].ColumnName.Contains("Time"))
                        {
                            continue;
                        }
                        SensorValueModel data = new SensorValueModel();
                        string IDCode = table.Columns[i].ColumnName;
                        var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                        data.Name = rass.Describe.Trim();
                        data.Value = (Convert.ToDouble(table.Rows[0][i].ToString())*rass.Scaler).ToString();
                        data.IDCode = IDCode;
                        data.Scaler = Convert.ToDouble(rass.Scaler);
                        data.Address = rass.Address.Trim();
                        data.Name = rass.Describe.Trim();
                        data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                        data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                        sensor.SensorValue.Add(data);
                    }
                    sensors.Add(sensor);
                }
            }
            if (sensors.Count > 0)
            {
                return Json(new { status = "0", data = sensors }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { status = "3" }, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult FixedSensor(string wellid)
        {
            R_ADJU_StructureService R_ADJU_StructureService = new R_ADJU_StructureService();
            var rasss = R_ADJU_StructureService.All().ToList();
            DataTable rai = new DataTable();
            DataTable rac = new DataTable();
            DataTable rae = new DataTable();
            List<SensorModel> sensors = new List<SensorModel>();
            using (var Db = new DBContainer())
            {
                string sql1 = "SELECT TOP 1 * FROM R_ADJU_IMPORTANT WHERE Well_ID = " + wellid + " order by Time desc ";
                rai = ResultHelper.sqlQueryForDataTatable(Db.Database, sql1).Copy();
                string sql2 = "SELECT TOP 1 * FROM R_ADJU_CONV WHERE Well_ID = " + wellid + " order by Time desc ";
                rac = ResultHelper.sqlQueryForDataTatable(Db.Database, sql2).Copy();
                string sql3 = "SELECT TOP 1 * FROM R_ADJU_EMETER WHERE Well_ID = " + wellid + " order by Time desc ";
                rae = ResultHelper.sqlQueryForDataTatable(Db.Database, sql3).Copy();
            }
            if (rai.Rows.Count > 0)
            {
                SensorModel sensor = new SensorModel();
                sensor.SensorValue = new List<SensorValueModel>();
                sensor.WellId = wellid;
                sensor.SensorName = "IMPORTANT";
                sensor.SensorChina = "智能电滚筒";
                for (int i = 0; i < rai.Columns.Count; i++)
                {
                    if (rai.Columns[i].ColumnName.Contains("ID") || rai.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    SensorValueModel data = new SensorValueModel();
                    string IDCode = rai.Columns[i].ColumnName;
                    var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                    data.Name = rass.Describe.Trim();
                    data.Value = (Convert.ToDouble(rai.Rows[0][i].ToString())*rass.Scaler).ToString();
                    data.IDCode = IDCode;
                    data.Scaler = Convert.ToDouble(rass.Scaler);
                    data.Address = rass.Address.Trim();
                    data.Name = rass.Describe.Trim();
                    data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                    data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                    sensor.SensorValue.Add(data);
                }
                sensors.Add(sensor);
            }
            if (rac.Rows.Count > 0)
            {
                SensorModel sensor = new SensorModel();
                sensor.SensorValue = new List<SensorValueModel>();
                sensor.WellId = wellid;
                sensor.SensorName = "CONV";
                sensor.SensorChina = "变频器（设备）";
                for (int i = 0; i < rac.Columns.Count; i++)
                {
                    if (rac.Columns[i].ColumnName.Contains("ID") || rac.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    SensorValueModel data = new SensorValueModel();
                    string IDCode = rac.Columns[i].ColumnName;
                    var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                    data.Name = rass.Describe.Trim();
                    data.Value = (Convert.ToDouble(rac.Rows[0][i].ToString())*rass.Scaler).ToString();
                    data.IDCode = IDCode;
                    data.Scaler = Convert.ToDouble(rass.Scaler);
                    data.Address = rass.Address.Trim();
                    data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                    data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                    sensor.SensorValue.Add(data);
                }
                sensors.Add(sensor);
            }
            if (rae.Rows.Count > 0)
            {
                SensorModel sensor = new SensorModel();
                sensor.SensorValue = new List<SensorValueModel>();
                sensor.WellId = wellid;
                sensor.SensorName = "EMETER";
                sensor.SensorChina = "智能电表（设备）";
                for (int i = 0; i < rae.Columns.Count; i++)
                {
                    if (rae.Columns[i].ColumnName.Contains("ID") || rae.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    SensorValueModel data = new SensorValueModel();
                    string IDCode = rae.Columns[i].ColumnName;
                    var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                    data.Name = rass.Describe.Trim();
                    data.Value = (Convert.ToDouble(rae.Rows[0][i].ToString())*rass.Scaler).ToString();
                    data.IDCode = IDCode;
                    data.Scaler = Convert.ToDouble(rass.Scaler);
                    data.Address = rass.Address.Trim();
                    data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                    data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                    sensor.SensorValue.Add(data);
                }
                sensors.Add(sensor);
            }
            if (sensors.Count > 0)
            {
                return Json(new { status = "0", data = sensors }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { status = "3" }, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult Configuration(string wellid, string sensorname)
        {
            Sensor_StructureService Sensor_StructureService = new Sensor_StructureService();
            DataTable conf = new DataTable();
            var ssss = Sensor_StructureService.All().ToList();
            using (var Db = new DBContainer())
            {
                string sql = "SELECT TOP 1 * FROM SENS_" + sensorname + " WHERE Well_ID = " + wellid + " order by Time desc ";
                conf = ResultHelper.sqlQueryForDataTatable(Db.Database, sql).Copy();
            }
            List<KeyValueModel> KeyValueListModel = new List<KeyValueModel>();
            if (conf.Rows.Count > 0)
            {
                for (int i = 0; i < conf.Columns.Count; i++)
                {
                    if (conf.Columns[i].ColumnName.Contains("ID") || conf.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    KeyValueModel data = new KeyValueModel();
                    string IDCode = conf.Columns[i].ColumnName;
                    var sss = ssss.Find(c => c.IDCode.Trim() == IDCode);
                    data.Key = sss.Describe;
                    data.Value = conf.Rows[0][i].ToString();
                    KeyValueListModel.Add(data);
                }
            }
            if (KeyValueListModel.Count > 0)
            {
                return Json(new { status = "0", data = KeyValueListModel }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { status = "3" }, JsonRequestBehavior.AllowGet);
            }
        }
        public string[] eng2chaandpow(string engname, R_SIGN_METER_BATT_POW rsmbp)
        {
            string[] str = new string[2];
            switch (engname)
            {
                case "LOAD_DISP":
                    str[0] = "载荷位移一体化传感器";
                    str[1] = rsmbp.MW1126;
                    break;
                case "LOAD":
                    str[0] = "载荷传感器";
                    str[1] = rsmbp.MW1127;
                    break;
                case "DISP":
                    str[0] = "位移传感器";
                    str[1] = rsmbp.MW1128;
                    break;
                case "O_PRESS":
                    str[0] = "油压传感器";
                    str[1] = rsmbp.MW1129;
                    break;
                case "O_TEMP":
                    str[0] = "油温传感器";
                    str[1] = rsmbp.MW1130;
                    break;
                case "CAS_PRESS":
                    str[0] = "套压传感器";
                    str[1] = rsmbp.MW1131;
                    break;
                case "MANIF_PRESS":
                    str[0] = "汇管压力传感器";
                    str[1] = rsmbp.MW1132;
                    break;
                case "MANIF_TEMP":
                    str[0] = "汇管温度传感器";
                    str[1] = rsmbp.MW1133;
                    break;
                case "RESV_L_LEV":
                    str[0] = "井口储罐液位仪";
                    str[1] = rsmbp.MW1134;
                    break;
                case "HEAT_STACK_TEMP":
                    str[0] = "加热炉烟囱温度传感器";
                    str[1] = rsmbp.MW1135;
                    break;
                case "HEAT_O_TEMP":
                    str[0] = "加热炉油温传感器";
                    str[1] = rsmbp.MW1136;
                    break;
                case "WJACK_L_LEV":
                    str[0] = "水套液位传感器";
                    str[1] = rsmbp.MW1137;
                    break;
                case "MIX_WDV":
                    str[0] = "掺稀配水阀";
                    str[1] = rsmbp.MW1138;
                    break;
                case "PRESS_TEMP":
                    str[0] = "温度压力一体化传感器";
                    str[1] = rsmbp.MW1141;
                    break;
                case "WL_DCENT_SWIT":
                    str[0] = "无线死点开关传感器";
                    str[1] = rsmbp.MW1142;
                    break;
                default:
                    str[0] = "其他表项";
                    str[1] = "0";
                    break;
            }
            return str;
        }
        public void AdjustAsync(string data)
        {
            AsyncManager.OutstandingOperations.Increment(1);

            string wellid = data.Split(',')[0];
            string wellstr = Session["wellstr"].ToString();
            string result,data1 =null;

            Task.Factory.StartNew(() =>
            {
                if (Session["identity"].ToString() != "Worker" && (wellstr == "0" || wellstr.Contains("-" + wellid + "-")))
                {
                    TcpConnect tc = new TcpConnect();
                    tc.clean();
                    int returndata = tc.ConnectTcp(data);
                    result = returndata.ToString();
                    data1 = tc.getSuccessstring();
                }
                else
                {
                    result = "-10";
                }
                AsyncManager.Parameters["result"] = result;
                AsyncManager.Parameters["data1"] = data1;
                AsyncManager.OutstandingOperations.Decrement();
            });
        }
        public JsonResult AdjustCompleted(string result, string data1)
        {
            return Json(new { status = result,data = data1 }, JsonRequestBehavior.AllowGet);
        }
        // GET: Adjust
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Config()
        {
            return View();
        }
        public JsonResult RefreshOneSensor(string wellid, string sensorname)
        {
            R_ADJU_StructureService R_ADJU_StructureService = new R_ADJU_StructureService();
            R_SIGN_METER_BATT_POWService R_SIGN_METER_BATT_POWService = new R_SIGN_METER_BATT_POWService();
            var rasss = R_ADJU_StructureService.All().ToList();
            var rsmbps = R_SIGN_METER_BATT_POWService.FindAll(c => c.Well_ID == wellid);
            var rsmbp = rsmbps.FirstOrDefault(c => c.Time == rsmbps.Max(d => d.Time));
            SensorModel sensor = new SensorModel();
            DataTable table = new DataTable();
            using (var Db = new DBContainer())
            {
                string sql1 = "SELECT TOP 1 * FROM R_ADJU_" + sensorname + " WHERE Well_ID = " + wellid + " order by Time desc ";
                table = ResultHelper.sqlQueryForDataTatable(Db.Database, sql1).Copy();
            }
            if (table.Rows.Count > 0)
            {
                string[] chaandpow = eng2chaandpow(sensorname, rsmbp);
                sensor.SensorValue = new List<SensorValueModel>();
                sensor.WellId = wellid;
                sensor.Power = chaandpow[1].Trim();
                sensor.SensorName = sensorname;
                sensor.SensorChina = chaandpow[0];
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (table.Columns[i].ColumnName.Contains("ID") || table.Columns[i].ColumnName.Contains("Time"))
                    {
                        continue;
                    }
                    SensorValueModel data = new SensorValueModel();
                    string IDCode = table.Columns[i].ColumnName;
                    var rass = rasss.Find(c => c.IDCode.Trim() == IDCode);
                    data.Name = rass.Describe.Trim();
                    data.Value = (Convert.ToDouble(table.Rows[0][i].ToString()) * rass.Scaler).ToString();
                    data.IDCode = IDCode;
                    data.Scaler = Convert.ToDouble(rass.Scaler);
                    data.Address = rass.Address.Trim();
                    data.Name = rass.Describe.Trim();
                    data.Unit = rass.Unit == null ? "" : rass.Unit.Trim();
                    data.Range = rass.Range == null ? "暂无" : rass.Range.Trim();
                    sensor.SensorValue.Add(data);
                }
            }
            if (sensor.SensorValue.Count > 0)
            {
                return Json(new { status = "0", data = sensor }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { status = "3" }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}